package com.mine.frame.mylandemo.receiver

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkInfo
import android.util.Log


/**
 * @Date 2022/11/4
 * Description:网络广播接收器
 */
class NetworkReceiver : BroadcastReceiver() {
    companion object {
        private const val TAG = "NetworkReceiver "
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        Log.e(TAG ,"收到广播 : onReceive")
        intent?.action?.let { action ->
            when(action){
                "android.media.VOLUME_CHANGED_ACTION" ->{
                    Log.e(TAG,"音量改变")
                }
                ConnectivityManager.CONNECTIVITY_ACTION ->{
                    context?.let { greaterLOLLIPOP(it) }
                }
                else->{
                    Log.e(TAG,"action :$action")
                }
            }
        }
    }


    private fun greaterLOLLIPOP(context: Context) {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var isConnect = false
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            val networkInfos: Array<NetworkInfo> = connMgr.getAllNetworkInfo()
            for (tempNetworkInfo in networkInfos) {
                if (tempNetworkInfo.isConnected) {
                    isConnect = true
                }
            }
        } else {
            val networkCapabilities = connMgr.getNetworkCapabilities(connMgr.activeNetwork)
            networkCapabilities?.let {
                isConnect = it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || it.hasTransport(
                    NetworkCapabilities.TRANSPORT_CELLULAR
                )
            }
        }
        Log.e(TAG, "isConnectNetWork : $isConnect")

    }
}